package utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    private static Connection connection = null;

    public static Connection getConnection(){
        if (connection == null) {
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

            InputStream stream = systemClassLoader.getResourceAsStream("jdbc.properties");

            Properties properties = new Properties();
            try {
                properties.load(stream);

                String driver = properties.getProperty("driver");
                String url = properties.getProperty("url");
                String user = properties.getProperty("user");
                String password = properties.getProperty("password");

                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (IOException | ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }

        }
        return connection;
    }

    public static void closeConnection(){
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
